const moment = require("moment");
const Base = require("./base");
module.exports = class Singin extends Base {
  // 获得用户最新签到情况
  getYesterdaySign(uid) {
    const sql = `SELECT SUM(\`count\`) AS total FROM sign WHERE \`uid\`='${uid}';SELECT \`count\`,create_time,sign_time FROM sign WHERE \`uid\`='${uid}' AND (DATE(\`sign_time\`)=DATE_SUB(CURDATE(), INTERVAL 1 DAY) OR DATE(\`sign_time\`)=CURDATE())`;
    return this.app.mysql
      .use("user")
      .query(sql)
      .then((res) => res[0])
      .then((res) => {
        const total = parseInt(res[0][0].total || '0', 10);
        const data = res[1][0] || {};
        return {
          total,
          ...data,
        };
      });
  }
  updateSign(uid) {
    const sql = `SELECT COUNT(id) AS counts FROM sign WHERE uid='${uid}' AND `;
    // 查询今天签到情况
    const today_expr = `DATE(sign_time)=CURDATE()`;
    // 查询昨天签到情况
    const yesterday_expr = `DATE(sign_time)=DATE_SUB(CURDATE(), INTERVAL 1 DAY)`;
    const db = this.app.mysql.use("user");
    return db
      .query(`${sql}${today_expr};${sql}${yesterday_expr}`)
      .then((res) => res[0])
      .then((res) => {
        // 今天还未签到
        if (res[0][0].counts == 0) {
          const signTime = moment().format();
          let sql = `INSERT INTO sign(\`uid\`, \`count\`, \`sign_time\`) VALUES('${uid}', 1, '${signTime}')`;
          // 判断用户是否昨天签到过，如果存在则更新签到，即连续签到
          if (res[1][0].counts > 0) {
            sql = `UPDATE sign SET \`count\`=\`count\` + 1,\`sign_time\`='${signTime}' WHERE \`uid\`='${uid}'
          AND DATE(\`sign_time\`)=DATE_SUB(CURDATE(), INTERVAL 1 DAY)`;
          }
          return db.query(sql).then(() => ({
            status: 0, // 签到成功
            message: "签到成功",
          }));
        } else {
          return {
            status: 1, // 已经签到过了
            message: "已经签到过了",
          };
        }
      });
  }
};
